package com.mingxun.project.base;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.mingxun.project.R;
import com.mingxun.project.listener.LifeCycleListener;
import com.mingxun.project.util.LoadingUtils;
import com.utilmodule.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * class name：
 *
 * @author liuhongyuan.
 * @date 2017/12/20
 */

public abstract class BaseFragment extends Fragment implements BaseView {
    public Activity mActivity;
    private KProgressHUD hud;
    //是否可见状态
    private boolean isVisible;
    //View已经初始化完成
    private boolean isPrepared;
    //是否第一次加载完
    private boolean isFirstLoad = true;

    protected abstract int getLayoutResource();

    protected abstract void onInitView(Bundle savedInstanceState);

    protected abstract void onInitData();

    protected abstract boolean isBindEventBusHere();

    protected abstract void initPresenter();

    protected abstract void lazyLoadData();

    private FrameLayout contentLayout;

    private View loadingLayout,emptyLayout,errorLayout;

    Unbinder unbinder;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        isFirstLoad = true;
        isPrepared = true;
        View view = inflater.inflate(R.layout.activity_base_layout, null);
        View successView = View.inflate(mActivity, getLayoutResource(), null);
        loadingLayout = view.findViewById(R.id.loading_layout);
        emptyLayout = view.findViewById(R.id.empty_layout);
        errorLayout = view.findViewById(R.id.error_layout);

        contentLayout = (FrameLayout) view.findViewById(R.id.content_layout);
        contentLayout.addView(successView);
        if (getLayoutResource() != 0) {
            return inflater.inflate(getLayoutResource(),null);
        } else {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this, view);
        initPresenter();
        if (isBindEventBusHere()) {
            EventBus.getDefault().register(this);
        }
        onInitView(savedInstanceState);
        if(isFirstLoad) {
            onInitData();
            lazyLoad();
        }
    }

    @Override
    public void showMessage(String message) {
        showMessage("提示", message);
    }

    @Override
    public void showMessage(String title, String message) {
        AlertDialog dialog = new AlertDialog.Builder(mActivity).setTitle(title).setMessage(message).setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).setPositiveButton("ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLUE);
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
    }

    @Override
    public void showToast(String msg) {
        ToastUtils.show(mActivity,msg,1000);
    }

    @Override
    public void showDialog(String message) {
        if (hud != null) {
            hud.show();
            return;
        }
        hud = KProgressHUD.create(mActivity)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel(message)
//                .setDetailsLabel(message)
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
    }

    @Override
    public void hideDialog() {
        if(hud != null) {
            hud.dismiss();
        }
    }

    @Override
    public void initRecyclerView(RecyclerView recyclerView, int orientation) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(orientation);
        recyclerView.setNestedScrollingEnabled(false);
    }

    @Override
    public void initGridRecyclerView(RecyclerView recyclerView, int orientation, int column) {
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), column);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的 OrientationHelper.VERTICAL
        layoutManager.setOrientation(orientation);
        recyclerView.setNestedScrollingEnabled(false);
    }

    public void onLoadingView(int state) {
        switch (state){
            case LoadingUtils.STATE_UNLOADED:
            case LoadingUtils.STATE_LOADING:
                contentLayout.setVisibility(View.GONE);
                loadingLayout.setVisibility(View.VISIBLE);
                emptyLayout.setVisibility(View.GONE);
                errorLayout.setVisibility(View.GONE);
                break;
            case LoadingUtils.STATE_ERROR:
                contentLayout.setVisibility(View.GONE);
                loadingLayout.setVisibility(View.GONE);
                emptyLayout.setVisibility(View.GONE);
                errorLayout.setVisibility(View.VISIBLE);
                break;
            case LoadingUtils.STATE_EMPTY:
                contentLayout.setVisibility(View.GONE);
                loadingLayout.setVisibility(View.GONE);
                emptyLayout.setVisibility(View.VISIBLE);
                errorLayout.setVisibility(View.GONE);
                break;
            case LoadingUtils.STATE_SUCCEED:
                contentLayout.setVisibility(View.VISIBLE);
                loadingLayout.setVisibility(View.GONE);
                emptyLayout.setVisibility(View.GONE);
                errorLayout.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 回调函数
     */
    public LifeCycleListener mListener;

    public void setOnLifeCycleListener(LifeCycleListener listener) {
        mListener = listener;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getUserVisibleHint()){
            isVisible = true;
            onVisible();
        }else {
            isVisible = false;
            onInvisible();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            isVisible = true;
            onVisible();
        }else {
            isVisible = false;
            onInvisible();
        }
    }

    protected void onVisible(){
        lazyLoad();
    }

    protected void onInvisible(){}

    protected void lazyLoad(){
        if(!isPrepared || !isVisible || !isFirstLoad) return;
        isFirstLoad = false;
        lazyLoadData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (isBindEventBusHere()) {
            EventBus.getDefault().unregister(this);
        }
    }
}
